const os = require('os');
const { exec } = require('child_process');
const express = require('express');

const utils = {
    getIps() {
        const interfaces = os.networkInterfaces();
        var IPAdress = '';
        for (var devName in interfaces) {
            let iface = interfaces[devName];
            let str = "";
            for (let i = 0; i < iface.length; i++) {
                let alias = iface[i];
                if (alias.family === 'IPv4' && !alias.internal) {
                    str += "  " + alias.address + ";";
                }
            }
            if (str.length > 0) {
                IPAdress += devName + ":\n" + str + "\n";
            }
        }
        return IPAdress;
    },

    getHostname() {
        return os.hostname;
    },

    getTcpPorts(cb) {        
        exec('netstat -ano', (error, stdout, stderr) => {
            if (error) {
                console.error(`error: ${error}`);
                cb("");
                return;
            }
            let strs = stdout.substring(stdout.indexOf('TCP')).split('\r\n');
            let ports = "";
            for (let i = 0; i < strs.length; i++) {
                if (strs[i].indexOf('TCP') >= 0) {
                    let c = strs[i].match(/\S+/g);
                    if (c[1][0] != '[') {
                        ports += `tcp: ${c[1]} on pid ${c[4]}, by remote ${c[2]} \n`;
                    }
                }
            }
            cb(ports);
        });
    },

    getTasklist(cb) {        
        exec('tasklist', (error, stdout, stderr) => {
            if (error) {
                console.error(`error: ${error}`);
                cb("");
                return;
            }
            let strs = stdout.substring(stdout.indexOf('====\r\n') + 6);
            cb(strs);
        });
    },

    remoteCV() {
        var app = express();
        app.msg = [];
        app.get('/', (req, res, next) => {
            if (req.query && req.query['cv']) {
                app.msg.push(req.query['cv']);
            }
            let str = "<div>";
            app.msg.forEach((e) => {
                if (e.indexOf("http") == 0) {
                    str += `<a href=${e}>${e}</a><br>`;
                } else {
                    str += `<p>${e}</p>`;
                }
            });
            str += "</div><hr><a href='/'>刷新</a><hr>";
            str += `<div><form action="/" method="get"><input name="cv" type="text" value=""/><input type="submit" value="Send"/></form></div>`;
            res.setHeader("Content-Type", "text/html;charset=utf-8");
            res.end(str);
        });
        app.listen(2313);
        return app;
    },
};

module.exports = utils;